package HttpUtils

import (
	"net/http"
	"io/ioutil"
	"strings"
)

var DEFAULT_HEADER = make(map[string]string)

func init(){
	DEFAULT_HEADER["CLIENT-PROCESS"]="KANMARS.SN"
}

func Get(url string)(string,error){
	client := http.Client{}
	req,err := http.NewRequest("GET",url,nil)
	if(err!=nil){
		return "",err
	}

	for headerName,headerValue := range DEFAULT_HEADER {
		req.Header.Set(headerName,headerValue)
	}
	resp,err := client.Do(req)
	if(err!=nil){
		return "",err
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "",err
	}
	return string(body),nil
}
func GetByHeader(url string,header map[string]string)(string,error){

	client := http.Client{}
	req,err := http.NewRequest("GET",url,nil)
	if(err!=nil){
		return "",err
	}

	for headerName,headerValue := range DEFAULT_HEADER {
		req.Header.Set(headerName,headerValue)
	}
	for headerName,headerValue := range header {
		req.Header.Set(headerName,headerValue)
	}
	resp,err := client.Do(req)
	if(err!=nil){
		return "",err
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "",err
	}
	return string(body),nil
}
func Post(url string,content string)(string,error){
	client := http.Client{}
	req,err := http.NewRequest("POST",url,strings.NewReader(content))
	if(err!=nil){
		return "",err
	}

	for headerName,headerValue := range DEFAULT_HEADER {
		req.Header.Set(headerName,headerValue)
	}
	resp,err := client.Do(req)
	if(err!=nil){
		return "",err
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "",err
	}
	return string(body),nil
}
func PostByHeader(url string,content string,header map[string]string)(string,error){

	client := http.Client{}
	req,err := http.NewRequest("GET",url,strings.NewReader(content))
	if(err!=nil){
		return "",err
	}

	for headerName,headerValue := range DEFAULT_HEADER {
		req.Header.Set(headerName,headerValue)
	}
	for headerName,headerValue := range header {
		req.Header.Set(headerName,headerValue)
	}
	resp,err := client.Do(req)
	if(err!=nil){
		return "",err
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "",err
	}
	return string(body),nil
}


func DoRequest(method string,url string,content string, header map[string]string)(int,string,map[string][]string,error){
	client := http.Client{}
	req,err := http.NewRequest(method,url,strings.NewReader(content))
	if(err!=nil){
		return 0,"",nil,err
	}

	for headerName,headerValue := range DEFAULT_HEADER {
		req.Header.Set(headerName,headerValue)
	}
	for headerName,headerValue := range header {
		req.Header.Set(headerName,headerValue)
	}
	resp,err := client.Do(req)
	if(err!=nil){
		return 555,"",nil,err
	}
	var rspcode = resp.StatusCode
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 555,"",nil,err
	}
	return rspcode,string(body),resp.Header,nil
}
